package cn.felord.jsr303springboot.exception;


import cn.felord.jsr303springboot.common.Rest;
import cn.felord.jsr303springboot.common.RestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *   统一异常处理
 *
 * @author Dax
 * @since 13 :31  2019-04-11
 */
@Slf4j
@RestControllerAdvice (basePackages = {"cn.felord.jsr303springboot.api"})
public class ApiExceptionHandler {

    /**
     * Handle rest.
     *
     * @param request the request
     * @param e       the e
     * @return the rest
     */
    @ExceptionHandler(Exception.class)
    public Rest handle(HttpServletRequest request, Exception e) {
        String contentType = request.getHeader("Content-Type");
        log.error("统一异常处理 uri: {} content-type: {} exception: {}", request.getRequestURI(), contentType, e.toString());
        if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            List<ObjectError> allErrors = bindException.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            return RestBody.failure(700, objectError.getDefaultMessage());
        }

        if (e instanceof HttpMessageNotReadableException) {
            return RestBody.failure(700, "请求参数非法！");
        }

        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
            ObjectError objectError = allErrors.get(0);
            return RestBody.failure(700, objectError.getDefaultMessage());
        }

        return RestBody.failure(700, "出错啦，请稍后再试！");
    }

}
